<template>
  <div class="member-level">
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="80px" inline>
        <el-form-item label="等级名称">
          <el-input v-model="searchForm.name" placeholder="请输入等级名称" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="enabled" />
            <el-option label="禁用" value="disabled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>会员等级</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleAdd">新增等级</el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="levelList" stripe style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="等级ID" width="80" />
        <el-table-column prop="name" label="等级名称" />
        <el-table-column prop="code" label="等级代码" />
        <el-table-column prop="discount" label="折扣率" width="100">
          <template #default="scope">
            {{ scope.row.discount }}%
          </template>
        </el-table-column>
        <el-table-column prop="benefits" label="特权" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="enabled"
              inactive-value="disabled"
              @change="handleStatusChange(scope.row)"
            />
            <el-tag :type="scope.row.status === 'enabled' ? 'success' : 'danger'" style="margin-left: 10px">
              {{ scope.row.status === 'enabled' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 等级编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="levelFormRef"
        :model="levelForm"
        :rules="levelFormRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="等级名称" prop="name">
              <el-input v-model="levelForm.name" placeholder="请输入等级名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="等级代码" prop="code">
              <el-input v-model="levelForm.code" placeholder="请输入等级代码" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="折扣率" prop="discount">
              <el-input-number
                v-model="levelForm.discount"
                :min="0"
                :max="100"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="levelForm.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="启用" value="enabled" />
                <el-option label="禁用" value="disabled" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="特权描述" prop="benefits">
          <el-input
            v-model="levelForm.benefits"
            type="textarea"
            :rows="3"
            placeholder="请输入特权描述"
          />
        </el-form-item>
        
        <el-form-item label="详细描述" prop="description">
          <el-input
            v-model="levelForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入详细描述"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveLevel" :loading="saveLoading">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useMemberStore } from '@/stores'

// 使用会员store
const memberStore = useMemberStore()

// 搜索表单
const searchForm = reactive({
  name: '',
  status: ''
})

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: computed(() => memberStore.levelTotal)
})

// 等级列表（从store中获取）
const levelList = computed(() => memberStore.levelList)
const loading = computed(() => memberStore.loading)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const saveLoading = ref(false)
const levelFormRef = ref()

// 等级表单
const levelForm = reactive({
  id: null,
  name: '',
  code: '',
  discount: 0,
  benefits: '',
  description: '',
  status: 'enabled'
})

// 等级表单验证规则
const levelFormRules = {
  name: [
    { required: true, message: '请输入等级名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入等级代码', trigger: 'blur' }
  ],
  discount: [
    { required: true, message: '请输入折扣率', trigger: 'blur' }
  ],
  benefits: [
    { required: true, message: '请输入特权描述', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 获取等级列表
const fetchLevelList = async () => {
  const params = {
    page: pagination.currentPage,
    pageSize: pagination.pageSize,
    name: searchForm.name,
    status: searchForm.status
  }
  
  try {
    await memberStore.fetchLevelList(params)
  } catch (error) {
    ElMessage.error('获取等级列表失败')
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchLevelList()
}

// 处理重置
const handleReset = () => {
  searchForm.name = ''
  searchForm.status = ''
  pagination.currentPage = 1
  fetchLevelList()
}

// 处理新增等级
const handleAdd = () => {
  dialogTitle.value = '新增等级'
  isEdit.value = false
  dialogVisible.value = true
  
  // 重置表单
  levelForm.id = null
  levelForm.name = ''
  levelForm.code = ''
  levelForm.discount = 0
  levelForm.benefits = ''
  levelForm.description = ''
  levelForm.status = 'enabled'
}

// 处理编辑等级
const handleEdit = (row) => {
  dialogTitle.value = '编辑等级'
  isEdit.value = true
  dialogVisible.value = true
  
  // 填充表单数据
  Object.assign(levelForm, row)
}

// 处理保存等级
const handleSaveLevel = () => {
  if (!levelFormRef.value) return
  
  levelFormRef.value.validate(async (valid) => {
    if (valid) {
      saveLoading.value = true
      
      try {
        if (isEdit.value) {
          await memberStore.updateLevel(levelForm.id, levelForm)
          ElMessage.success('更新成功')
        } else {
          await memberStore.createLevel(levelForm)
          ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        await fetchLevelList()
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新失败' : '新增失败')
      } finally {
        saveLoading.value = false
      }
    }
  })
}

// 处理删除等级
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除会员等级 "${row.name}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await memberStore.deleteLevel(row.id)
      ElMessage.success('删除成功')
      await fetchLevelList()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 处理状态变更
const handleStatusChange = async (row) => {
  try {
    await memberStore.updateLevel(row.id, { status: row.status })
    ElMessage.success('状态更新成功')
  } catch (error) {
    ElMessage.error('状态更新失败')
    // 恢复原状态
    row.status = row.status === 'enabled' ? 'disabled' : 'enabled'
  }
}

// 处理对话框关闭
const handleDialogClose = () => {
  if (levelFormRef.value) {
    levelFormRef.value.resetFields()
  }
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchLevelList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchLevelList()
}

// 组件挂载后获取等级列表
onMounted(() => {
  fetchLevelList()
})
</script>

<style lang="scss" scoped>
.member-level {
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>